<template>
  <dragTree
    :value="dataTree"
    v-bind="treeProps"
    ref="_refTree"
    @createNode="createNode"
    @deleteNode="deleteNode"
    @clickNode="clickNode"
    @drop="drop"
    :style="styles"
  >
    <Form v-if="childData.length && !['root'].includes(formData.name)"
      :model="formData" :label-width="90" label-position="right" class="rightForm">
        <Row >
          <Col v-for="(item,index) in fieldList" :key="index" :span="item.span || 24">
            <FieldItem
              v-model="formData[item.key]" :config="item.config"
              :formItemProps="{label: item.title, labelWidth: item.labelWidth, prop: item.key, }"
            />
          </Col>
          <Col :span="24" class="propertyWp" v-if="this.hierObject.hasProperties">
            <Alert style="margin: 0">{{ $t(`model.modelProperties`)}}</Alert>
            <cfgModelPropertyNoGroup ref="_properties" v-model="formData.properties"/>
            <Alert style="margin: 0">{{ $t(`model.modelStatusProperties`)}}</Alert>
            <cfg-modelStatusProperty v-model="formData.statusProperties"/>
          </Col>
        </Row>
    </Form>
    <span class="split"></span>
  </dragTree>
</template>

<script>
import hierUtil from './util'
export default {
  name: "cfgHierTree",
  data() {
    return {
      treeProps: {
        width: '220px',
        // maxLevel: 1,
        treeConfig: {
          expandOnClickNode: false,
          currentNodeKey: 'root',
          draggable: false,
          nodeKey: 'nodeId',
          props: {
            label: 'name',
          }
        },
      },
      curNode: {},
      formData: this.hierObject.rootTpl(),
      styles: {
        minHeight: '200px'
      }
    }
  },
  created() {
  },
  methods:  {
    clickNode(nodeData = {}, node) {
      let newData = this.findChild(nodeData)
      this.curNode = node
      this.saveItem() // 节点切换后，需要先保存上一个节点的数据
      if (!node.isLeaf && newData.name !== 'root') {
        newData.nodeType = 'node'
      }
      this.formData = newData
    },
    // 新增节点：读取默认data
    createNode(type, currentNode) {
      let newItem = {
        ...this.hierObject.itemTpl(),
        parentId: type === 'inner' ? currentNode.data.nodeId : currentNode.data.parentId,
        // name: '新增节点',
      }
      let _this = this.$refs._refTree
      let index = this.findChildIndex(currentNode.data)

      if (type === 'inner') {
        _this.$refs.tree.append(newItem, currentNode)
        let child = this.childData.filter(item => item.parentId === currentNode.data.nodeId)
        index += 1 + child.length
        this.$nextTick(()=> {
          if(currentNode.data && this.formData.name !== 'root' && this.curNode.data.nodeId === currentNode.data.nodeId) {
            this.curNode.isLeaf = false
            this.formData.nodeType = 'node'
          }
        })
      } else if (type === 'before') {
        _this.$refs.tree.insertBefore(newItem, currentNode)
      } else {
        _this.$refs.tree.insertAfter(newItem, currentNode)
        index++
      }
      if (index !== false) {
          this.childData.splice(index, 0, newItem)
      } else {
        this.childData.push(newItem)
      }
    },
    // 拖动节点：update nodeData
    drop(draggingNode, dropNode, dropType, ev) {
      if (dropType === 'inner') {
        draggingNode.data.parentId = dropNode.data.nodeId
      } else {
        draggingNode.data.parentId = dropNode.data.parentId
      }
      let index = this.findChildIndex(draggingNode.data)
      // 先找到节点拖动前的index，删除记录
      if (index !== false) {
          this.childData.splice(index, 1)
      }
      // 然后在拖动后的index，插入记录
      index = this.findChildIndex(dropNode.data)
      if (index !== false) {
          this.childData.splice(index+1, 0, draggingNode)
      } else {
        this.childData.push(draggingNode)
      }
    },
    deleteNode(nodeData) {
      let _this = this.$refs._refTree
      let index = this.findChildIndex(nodeData)
      if (index !== false) {
        this.childData.splice(index, 1)
      }
      if (this.curNode.data.nodeId !== nodeData.nodeId) {
        this.saveItem()
      }
      this.formData = this.hierObject.rootTpl()
      _this.setCurrentKey('root')
    },
    change(val, name) {
      if(name === 'type') {
        this.formData.model = {}
      } else if (name === 'name' && this.$refs._refTree) {
        let _this = this.$refs._refTree
        _this.$set(_this.currentData, 'name', val)
      }
    },
    findChildIndex(tmpData = {}) {
      let index = this.childData.findIndex(item => item.nodeId == tmpData.nodeId)
      return index == -1 ? false : index
    },
    findChild(tmpData = {}) {
      return this.childData.find(item => item.nodeId == tmpData.nodeId) || {}
    },
    saveItem() {
      try {
        let res = this.formData
        let index = this.findChildIndex(res)

        if (res.name === 'root') {
          return;
        }
        if (index !== false) {
          this.childData.splice(index, 1, res)
        }
      }
      catch(err) {
        console.log("🚀 ~ file: cfgHierTree.vue:124 ~ saveItem ~ err:", err)
      }
    },
    // 构建表单字段信息
    buildFormField (item) {
        let field = {
            key: item.name,
            title: item.name,
        }
        switch (item.type) {
            case 'Double':
                field = {
                    ...field,
                    config: {
                      type: 'number',
                      min: 0,
                      max: 99999999,
                      precision: 2
                    }
                }
                break;
            case 'Integer':
                field = {
                    ...field,
                    config: {
                      type: 'number',
                      min: 0,
                      max: 99999999,
                      precision: 0
                    }
                }
                break;
            case 'Boolean':
                field = {
                    ...field,
                    config: {
                      type: 'check',
                    }
                }
                break;
            case 'DateTime':
                field = {
                    ...field,
                    config: {
                      type: 'datetime',
                    }
                }
                break;
            default:
                field = {
                    ...field,
                    config: {
                      type: 'text'
                    }
                }
                break;
        }
        return field;
    },
    checkValues() {
      return this.$refs._properties ? this.$refs._properties.checkValues() : true
    }
  },
  props: {
    hierObject: {
      default() {
        return null
      }
    },
    modelFieldList: {
      default() {
        return []
      }
    },
    isInstance: {
      default: false
    },
  },
  computed: {
    childData() {
      let res = this.hierObject && this.hierObject.hierProperties.content ? this.hierObject.hierProperties.content : [];
      return res
    },
    dataTree() {
      return this.hierObject && this.hierObject.recordsTree ? this.hierObject.recordsTree : []
    },
    fieldList() {
        return [
          ...hierUtil.fieldList(this.G_Locale, true),
          {
              key: 'nodeType',
              title: { 'zh-CN': '节点类型', 'en-US': 'node type' }[this.G_Locale],
              span: 12,
              config: {
                type: this.curNode.isLeaf ? 'select' : 'text',
                readonly: !this.curNode.isLeaf,
                options: hierUtil.nodeTypeOptions,
              },
          }
        ]
    },
  },
}
</script>

<style lang="less" scoped>
  .split {
    position: absolute;
    top: -16px;
    bottom: -16px;
    left: 220px;
    width: 1px;
    background-color: #eee;
  }
  .rightForm {
    min-height: 200px;
    flex: 1;
  }
</style>